package com.company.modules.project.service;

import com.company.datasource.annotation.DataSource;
import com.company.modules.project.util.MailClient;
import com.company.modules.project.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.concurrent.TimeUnit;

/**
 * @author : Real
 * @date : 2022/2/9 8:57
 * @description : 忘记密码，找回流程
 */
@Service
@DataSource("data-db")
public class ForgetPasswordService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MailClient mailClient;

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private EmployeeService employeeService;

    public void setVerifyCode(String email, String verify) {
        String verifyKey = RedisKeyUtil.getForgetPasswordVerifyKey(email);
        // 设置失效时间五分钟
        redisTemplate.opsForValue().set(verifyKey, verify, 60 * 5, TimeUnit.SECONDS);
    }

    public void sendForgetPasswordVerify(String subject, String email, String code) {
        // 发送验证码邮件
        Context context = new Context();
        context.setVariable("email", email);
        context.setVariable("verify", code);
        // 模板引擎调用网页，将其中的数据填充之后，生成一个 HTML 网页字符串对象，格式化网页
        String process = templateEngine.process("/mail/forget", context);
        mailClient.sendMail(email, subject, process);
    }

    public String getVerifyCode(String email) {
        String verifyKey = RedisKeyUtil.getForgetPasswordVerifyKey(email);
        return (String) redisTemplate.opsForValue().get(verifyKey);
    }

    public boolean deleteVerifyCode(String email) {
        String verifyKey = RedisKeyUtil.getForgetPasswordVerifyKey(email);
        return redisTemplate.opsForValue().getOperations().delete(verifyKey);
    }

}
